import DataPreferences from '@ohos.data.preferences';

class PreferencesUtil{
  //实例
  preferences: DataPreferences.Preferences | null = null;

  //创建实例
  async createPreferences(content){
    try {
      this.preferences = await DataPreferences.getPreferences(content, 'myPreferences');
      console.log('myPreferencesSuccess');
    }catch (err){
      console.log('myPreferencesErr', JSON.stringify(err));
    };
  };

  //设置
  async put(key: string, val: DataPreferences.ValueType){
    if(!this.preferences){
      console.log('preferencesErr', '实例未创建');
      return;
    }
    try{
      await this.preferences.put(key, val);
      await this.preferences.flush();
      console.log('putSuccess', `设置${key}成功`);
    }catch (err){
      console.log('putErr', `设置${key}失败`, JSON.stringify(err));
    }
  };

  //获取
  async get(key: string, defaults:DataPreferences.ValueType = '默认值'){
    if(!this.preferences){
      console.log('preferencesErr', '实例未创建');
      return;
    }
    try{
      let res = await this.preferences.get(key, defaults);
      console.log('getSuccess', `获取${key}成功`);
      return res;
    }catch (err){
      console.log('getErr', `获取${key}失败`, JSON.stringify(err));
    }
  };

  //获取
  async getAll(){
    if(!this.preferences){
      console.log('preferencesErr', '实例未创建');
      return;
    }
    try{
      let res = await this.preferences.getAll();
      console.log('getAllSuccess', `获取所有成功`);
      return res;
    }catch (err){
      console.log('getAllErr', `获取所有失败`, JSON.stringify(err));
    }
  };

  //获取
  async del(key: string){
    if(!this.preferences){
      console.log('preferencesErr', '实例未创建');
      return;
    }
    try{
      let res = await this.preferences.delete(key);
      console.log('delSuccess', `删除${key}成功`);
      return res;
    }catch (err){
      console.log('delErr', `删除${key}失败`, JSON.stringify(err));
    }
  }
}
export default new PreferencesUtil();